package com.example;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author Liuqz
 * @date 2018/11/17 21:52
 */
public class CollectorIntroduce {

    public static void main(String[] args) {

        List<Apple> list = Arrays.asList(new Apple("green", 150)
                , new Apple("yellow", 120)
                , new Apple("green", 170)
                , new Apple("green", 150)
                , new Apple("yellow", 120)
                , new Apple("green", 170));

        Optional.ofNullable(groupByNoraml(list)).ifPresent(System.out::println);
    }

    private static Map<String, List<Apple>> groupByNoraml(List<Apple> apples) {
        Map<String, List<Apple>> map = Maps.newHashMap();
        for (Apple apple : apples) {
            List<Apple> list = map.get(apple.getColor());
            if (CollectionUtils.isEmpty(list)) {
                list = Lists.newArrayList();
                map.put(apple.getColor(), list);
            }
            list.add(apple);
        }
        return map;
    }

    private static Map<String, List<Apple>> groupByFuncation(List<Apple> apples) {
        Map<String,List<Apple>> map = Maps.newHashMap();
        apples.stream().forEach(e -> {
            List<Apple> colorList = Optional.ofNullable(map.get(e.getColor())).orElseGet(() ->{
                List<Apple> list = Lists.newArrayList();
                map.put(e.getColor(), list);
                return list;
            });
            colorList.add(e);
        });
        return map;
    }

    private static Map<String, List<Apple>> groupByCollector(List<Apple> apples) {
        return apples.stream().collect(Collectors.groupingBy(Apple::getColor));
    }
}
